package com.mylg.craw.house.government;

import com.fasterxml.jackson.core.type.TypeReference;
import com.mylg.craw.house.government.category.Article;
import com.mylg.craw.house.government.category.CategoryItem;
import com.mylg.craw.house.util.JacksonUtils;
import jakarta.annotation.Resource;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestClient;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

@Service("governmentCrawListService")
public class CrawListService {
    @Resource
    private RestClient restClient;

    //page=1,2,3,4,5,6
    private static final String CATEGORY = "https://public.zhengzhou.gov.cn/action.jspx?tpl=action&sub=dir&cid=176291&did=19";

    private static final String LIST = "https://public.zhengzhou.gov.cn/?a=dir&d=19&c=176291&f=176375";

    private static final String TITLE = "统计信息";

    public int count() {
        String data = restClient.get().uri(CATEGORY).accept(MediaType.APPLICATION_JSON).retrieve().body(String.class);
        List<CategoryItem> res = JacksonUtils.readValue(data, new TypeReference<List<CategoryItem>>() {
        });
        if (res == null) {
            return 0;
        }
        return res.stream().filter(i -> TITLE.equals(i.getName())).findFirst().map(CategoryItem::getCount).orElse(0);
    }

    public List<Article> page(int page) {
        String url = LIST;
        if (page > 1) {
            url = url.concat("&page=" + page);
        }
        String data = restClient.get().uri(url).accept(MediaType.ALL).retrieve().body(String.class);
        return parseListHtml(data);
    }

    private List<Article> parseListHtml(String data) {
        List<Article> articles = new ArrayList<>();
        Document document = Jsoup.parse(data);
        Elements all = document.getElementsByClass("list_item_pubinfo_a");
        if (all.isEmpty()) {
            return Collections.emptyList();
        }
        for (Element element : all) {
            articles.add(parseArticle(element));
        }
        return articles;
    }

    private Article parseArticle(Element element) {
        Article article = new Article();
        article.setUrl(element.attr("href"));
        article.setTitle(element.text());
        Element sibling = element.nextElementSibling();
        if (sibling != null && sibling.hasClass("pubinfo-card")) {
            for (Element child : sibling.children()) {
                String label = child.getElementsByTag("i").first().attr("title").trim();
                String value = child.getElementsByTag("em").first().text();
                switch (label) {
                    case "索引号":
                        article.setIndex(value);
                        break;
                    case "发布机构":
                        article.setInstitution(value);
                        break;
                    case "关键词":
                        article.setKey(value);
                        break;
                    case "成文日期":
                        article.setCreateDate(value);
                        break;
                    case "发布日期":
                        article.setPublishDate(value);
                        break;
                }
            }
        }
        return article;
    }
}
